package com.tbb.app.common.filter;

import com.alibaba.fastjson.JSON;
import com.tbb.app.common.config.CustomProps;
import com.tbb.app.common.entity.BaseResponse;
import com.tbb.app.common.entity.UserInfo;
import com.tbb.app.common.exception.BusinessException;
import com.tbb.app.common.service.CurrentLoginUserService;
import com.tbb.app.common.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LiuSenLin
 * @date 2020/1/16 19:54
 */
@Slf4j
@Component
@Order(1)
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private CurrentLoginUserService currentLoginUserService;
    @Autowired
    private CustomProps customProps;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        long start = System.currentTimeMillis();
        String uri = request.getRequestURI();
        if (uri.startsWith(customProps.getApiPrefix()) && !customProps.getPermitUris().contains(uri)) {
            try {
                String token = request.getHeader("accessToken");
                UserInfo userInfo = tokenService.getUserInfo(token);
                currentLoginUserService.setAccessToken(token);
                currentLoginUserService.setUserInfo(userInfo);
            } catch (BusinessException e) {
                log.error("token异常", e);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().write(JSON.toJSONString(BaseResponse.instance(e.getErrorCode())));
                long end = System.currentTimeMillis();
                log.info("uri [{}] , total [{}] ms", uri, end - start);
                return;
            }
        }
        try {
            chain.doFilter(request, response);
        } catch (BusinessException b) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            BaseResponse<Object> result = BaseResponse.failed();
            result.setMessage(b.getMessage());
            response.getWriter().print(JSON.toJSONString(result));
        } finally {
            currentLoginUserService.removeUserInfo();
            long end = System.currentTimeMillis();
            log.info("uri [{}] , total [{}] ms", uri, end - start);
        }
    }
}
